﻿using System;
using System.Web.UI.WebControls;
using Cms.Utilities;
using Cms.Web.Framework.Plugins.Attributes;
using iLib.Web.UI;

namespace Cms.Web.Framework.Plugins
{
    public class SearchBox : BaseTemplatedPlugin
    {
        // Property fields
        private string _resultPage;

        // Template controls
        private TextBox txtQuery;
        
        [Browse("file")]
        public string ResultPage
        {
            get { return _resultPage; }
            set { _resultPage = value; }
        }

        public new string ID
        {
            get { return base.ID; }
            set { base.ID = value; }
        }
        protected override void CreateChildControls()
        {
            try
            {
                base.CreateChildControls();
                txtQuery = (TextBox)FindControl("txtQuery");
                var btnSearch = (Button)FindControl("btnSearch");
                var lbSearch = (LinkButton)FindControl("lbSearch");
                if (btnSearch != null)
                    btnSearch.Click += btnSearch_Click;
                if (lbSearch != null)
                    lbSearch.Click += lbSearch_Click;
            }
            catch (Exception ex)
            {
                Logging.LogError("SearchBox", ex);
                Controls.Clear();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            // Only set the text in search box if the search origins from itself
            if (RequestDetails.GetQueryStringValue("SearchBoxID") == this.ID)
            {
                txtQuery.Text = RequestDetails.GetQueryStringValue("q");
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Search();
        }

        private void lbSearch_Click(object sender, EventArgs e)
        {
            Search();
        }

        private void Search()
        {
            string url = Url.VirtualPath;
            if (RequestDetails.Locale != RequestDetails.Site.DefaultLocale &&
                !_resultPage.ToLower().StartsWith(RequestDetails.Locale.UrlCode + "/"))
                url += RequestDetails.Locale.UrlCode + "/";
            url += _resultPage + "?q=" + Server.UrlEncode(txtQuery.Text.Trim()) + "&SearchBoxID=" + Server.UrlEncode(ID);
            Response.Redirect(url);
        }
    }
}